package web.get;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.Chapter;
import service.BookService;
import service.impl.BookServiceImpl;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getChapterContent")
public class GetChapterContentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String cid =request.getParameter("cid");
        Map<String,Object> msg = new HashMap<>(8);
        ObjectMapper om = new ObjectMapper();
        BookService bs = new BookServiceImpl();
        if("".equals(cid)||"undefinded".equals(cid)||cid==null){
            //参数不存在
            msg.put("msg","参数错误");
            msg.put("isSuccess",false);
            om.writeValue(response.getOutputStream(),msg);
        }

        assert cid!=null;
        Chapter chapter = bs.getChapter(new Chapter().setCid(Integer.parseInt(cid)));
        Book book = ServletUtil.checkBook(ServletUtil.checkLogin(request), chapter.getBid());
        if(book==null){
            msg.put("msg","章节不可访问");
            msg.put("isSuccess",false);
            om.writeValue(response.getOutputStream(),msg);
        }
        msg.put("msg","成功");
        msg.put("isSuccess",true);
        msg.put("chapter",chapter);
        om.writeValue(response.getOutputStream(),msg);
    }
}
